package system;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/getStudentTestInf")
public class getStudentTestInf extends HttpServlet {
	private static final long serialVersionUID = 1L;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int type=Integer.parseInt(req.getParameter("type"));
    	
    	int partNo=Integer.parseInt(req.getParameter("partNo"));
		int questionNo=Integer.parseInt(req.getParameter("questionNo"));
		
		String result="";
		
		HttpSession session=req.getSession();
        String testid=(String)session.getAttribute("testid");
        String userid=(String)session.getAttribute("userid");
		
		sqlOperation sql = new sqlOperation();
		
		int userType = Integer.parseInt(sql.getQuerySet("select user_type from user_inf where user_id='"+userid+"'",1)[0]);
		if(userType==1) {
			userid=req.getParameter("userid");
		}

		if(type==1) {
			String[] inf = sql.getQueryLine("select student_answer,grade from student_question_single_selection where student_id='"+userid+"' and test_id='"+testid+"' and part_no='"+partNo+"' and question_no='"+questionNo+"'",2);
			result = "{\"answer\":\""+inf[0]+"\",\"grade\":\""+inf[1]+"\",\"code\":\""+0+"\"}";
		}else if(type==2) {
			String[] inf = sql.getQueryLine("select student_answer_A,student_answer_B,student_answer_C,student_answer_D,grade from student_question_multiple_selection where student_id='"+userid+"' and test_id='"+testid+"' and part_no='"+partNo+"' and question_no='"+questionNo+"'",5);
			String answer="";
			for(int i=0;i<4;i++) {
				if(!inf[i].equals("null")) {
					answer+=inf[i];
				}
			}
			result = "{\"answer\":\""+answer+"\",\"grade\":\""+inf[4]+"\",\"code\":\""+0+"\"}";
		}else if(type==3) {
			String[] inf = sql.getQueryLine("select student_answer,grade from student_question_subjective_topic where student_id='"+userid+"' and test_id='"+testid+"' and part_no='"+partNo+"' and question_no='"+questionNo+"'",2);
			int isFinished = Integer.parseInt(sql.getQueryLine("select isFinished from have_subject_topic where student_id='"+userid+"' and test_id='"+testid+"' and part_no='"+partNo+"' and question_no='"+questionNo+"'",1)[0]);
			if(isFinished==0) {
				result = "{\"answer\":\""+inf[0]+"\",\"code\":\""+3+"\"}";
			}else if(isFinished==1) {
				result = "{\"answer\":\""+inf[0]+"\",\"grade\":\""+inf[1]+"\",\"code\":\""+0+"\"}";
			}
		}
		
		resp.setContentType("application/json;charset=UTF-8");
		PrintWriter out = resp.getWriter();		
		out.write(result);
    }   
    
}
